import { _decorator, Component, Node } from 'cc';
import { BaseManager } from '../../libs/rxjs/cc3/BaseManager';
import { color } from 'cc';
import { director } from 'cc';
import { System } from 'cc';
import { native } from 'cc';
import { sys } from 'cc';
import { timem } from '../TimeManager';
import { thinking_sdk_m } from './ThinkingCocosSDKManager';
import { udm } from '../UserDataManager';
import { appsflyer_sdk_m } from './AppsFlyerSDKManager';
import { gm } from '../GameManager';
const { ccclass, property } = _decorator;

@ccclass('JsbSDKManager')
export class JsbSDKManager extends BaseManager {

    public static instance: JsbSDKManager;
    static ID = 'jsb_sdk_system';
    get logColorOverride() { return color().fromHEX('#EECCDD') };

    static registerSystem() {
        director.unregisterSystem(director.getSystem(JsbSDKManager.ID));
        director.registerSystem(JsbSDKManager.ID, jsb_sdk_m, System.Priority.MEDIUM);
        jsb_sdk_m.init();
    }

    onInitManager() {
        this.log('onInitManager', this.timestamp);
        if (sys.isNative) {
            native.bridge.onNative = (arg0: string, arg1: string): void => {
                // 先检查本Manager里面的监听，如果没有，则走兼容jsbBridgeWrapper的监听
                if (!this.dispatchMsg(arg0, arg1)) {
                    //@ts-ignore
                    // 如果使用了native-jsbBridgeWrapper，那么不应该使用native.bridge，就是因为这个onNative。此处做兼容，把消息传回native.jsbBridgeWrapper，就兼容了之前的native.jsbBridgeWrapper
                    // native.jsbBridgeWrapper.triggerEvent(arg0, arg1);
                }
            };
            this.registerMsg('JsbSDKManager.applicationDidBecomeActive', this.applicationDidBecomeActive.bind(this));
            this.registerMsg('JsbSDKManager.applicationWillResignActive', this.applicationWillResignActive.bind(this));
            this.registerMsg('JsbSDKManager.applicationDidEnterBackground', this.applicationDidEnterBackground.bind(this));
            this.registerMsg('JsbSDKManager.applicationWillEnterForeground', this.applicationWillEnterForeground.bind(this));
            this.registerMsg('JsbSDKManager.applicationWillTerminate', this.applicationWillTerminate.bind(this));
        }
    }

    callbackMap: Map<string, (string) => void> = new Map();

    registerMsg(msgName: string, callback: (string) => void) {
        this.callbackMap.set(msgName, callback);
    }

    dispatchMsg(msgName: string, arg: string): boolean {
        if (this.callbackMap.has(msgName)) {
            this.callbackMap.get(msgName)(arg);
            return true;
        }
        return false;
    }

    sendMsg(arg0: string, arg1: string) {
        if (sys.isNative) {
            native.bridge.sendToNative(arg0, arg1);
        }
    }

    startAt: number = null;

    firstLaunch() {
        this.log('@firstLaunch');
        this.startAt = timem.now();
    }

    applicationDidBecomeActive() {
        this.log('@applicationDidBecomeActive');
        this.startAt = timem.now();
        udm.scheduleNotification();
    }

    applicationWillResignActive() {
        this.log('@applicationWillResignActive');
        this.storeLaunchTime();
    }

    applicationDidEnterBackground() { // 进后台
        this.log('@applicationDidEnterBackground');
        udm.scheduleNotification();
    }

    applicationWillEnterForeground() {
        this.log('@applicationWillEnterForeground');
    }

    applicationWillTerminate() {
        this.log('@applicationWillTerminate');
    }

    storeLaunchTime(skipSave = false) {
        if (this.startAt != null) {
            // let duration = timem.now() - this.startAt;
            let duration = gm.activeDuration.value;
            udm.launchTime.value += duration;

            udm.launchTimeTotal.value += duration;
            if (!skipSave) udm.save();

            this.log('@ResignActive saved:', this.startAt, duration, udm.launchTimeTotal.value)
            if (timem.now() < udm.firstLoginAt.value + 86400 * 1000) {
                thinking_sdk_m.requestUserAdd({
                    NewUserPlayTime: Math.floor(duration / 1000)
                });
                appsflyer_sdk_m.check_af_r30r();
            }
            this.startAt = timem.now();
            gm.activeDuration.value = 0;
        }
    }

}

globalThis.JsbSDKManager = JsbSDKManager;

export const jsb_sdk_m = JsbSDKManager.instance = new JsbSDKManager();